package xyz.chaobei.springbootstudy.exception;

import lombok.extern.java.Log;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xyz.chaobei.springbootstudy.config.ErrorResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Log
public class GlobalExControllerHandler {

    @ExceptionHandler(value = BaseException.class)
    public ResponseEntity exceptionHandler(BaseException e, HttpServletRequest request) {
        log.info("exceptionHandler:" + e.toString());
        ErrorResponse response = new ErrorResponse(e, request.getRequestURI());
        return new ResponseEntity(response, new HttpHeaders(), e.getErrorCode().getStatus());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity methodArgumentNotValid(MethodArgumentNotValidException exception, HttpServletRequest request) {
        log.info("methodArgumentNotValid:" + exception.getMessage());

        Map<String,String> errorMsg = new HashMap<>();
        exception.getBindingResult().getAllErrors().forEach(objectError -> {
            String fieldName = ((FieldError) objectError).getField();
            errorMsg.put(fieldName,objectError.getDefaultMessage());
        });

        BaseException baseException = new RequestBadException();
        ErrorResponse response = new ErrorResponse(baseException, request.getRequestURI(),errorMsg);
        return new ResponseEntity(response, new HttpHeaders(), baseException.getErrorCode().getStatus());
    }

    /**
     * 消息无法读取异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ResponseEntity messageNotReadHandler(HttpMessageNotReadableException exception,HttpServletRequest request) {
        log.info("methodArgumentNotValid:" + exception.getMessage());

        BaseException baseException = new MessageNotReadException();
        ErrorResponse response = new ErrorResponse(baseException, request.getRequestURI());
        return new ResponseEntity(response, new HttpHeaders(), baseException.getErrorCode().getStatus());

    }


}
